import { GlobalFunction } from "../base/GlobalFunction";
import { ifEnemyData, bindData, ifIdOpr} from "../Data/dataBase";
import { netService } from "../netServices/netServices";

const { ccclass, property } = cc._decorator;

@ccclass
export default class enemyBase extends cc.Component {

    @property(cc.Node)
    hpBar: cc.Node = null;
    @property(cc.RigidBody)
    rgBody: cc.RigidBody = null;
    @property(cc.Node)
    modelBody:cc.Node = null;

    private _isDead: boolean = false;
    private _enemyId: number = null;
    private _Hp:number = 0;

    init(data: ifEnemyData) {
        this._enemyId = data.id;
        this._Hp = data.hp;
        this.hpBar.getComponent("enemyHpBar").init(data);
        bindData("WORLD_DATA", "DEL_ENEMY" + this._enemyId, this.onDie.bind(this), this);
        bindData("WORLD_DATA", "ENEMY_HP" + this._enemyId, this.onHpChange.bind(this), this);
    }

    async onHpChange(data){
        var ani = await GlobalFunction.asyncLoadPrefabEx("prefab/effect/floatNumber", this);
        var aniObj = cc.instantiate(ani);
        var p = cc.find("Canvas/UI");
        var pos = GlobalFunction.NodePosToUIPos(this.node);
        pos = p.convertToNodeSpaceAR(pos);
        aniObj.setPosition(pos);
        p.addChild(aniObj);
        aniObj.getComponent("aniFloatNumber").play(this._Hp - data.Hp);
        this._Hp = data.Hp;
    }

    onBeginContact(contact, selfCollider, otherCollider) {
        if(otherCollider.node.group != "bullet") return;
        if (this._isDead) return;
        
        var data:ifIdOpr = {
            id:this._enemyId,
            amount:-50,
        }
        netService.Ins().attackEnemy(data);
    }

    async onDie() {
        this._isDead = true;
        this.node.getComponent("fllowFunc").setFllowItem(null);
        this.rgBody.linearVelocity = cc.v2(0,0);
        this.node.getComponent(cc.Animation)
        await GlobalFunction.asyncPlayAnimationEx(this.node.getComponent(cc.Animation), "Die", this);
        this.node.destroy();
    }

    update(){
        if(this._isDead) return;

        if (this.modelBody) {
            this.modelBody.getComponent("modelBase").setDirection(GlobalFunction.getDirection(cc.v2(this.rgBody.linearVelocity)));
        }
    }
}
